package com.pj.sso;

import cn.dev33.satoken.sso.template.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.pj.project.sys_user.SysUser;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 封装SSO常用方法
 *
 * @author click33
 */
public class SsoMethodUtil {

    /**
     * 根据用户 id 获取 User 信息
     *
     * @param userId 用户id
     * @return User信息
     */
    public static SysUser getUserById(long userId) {
        // 调用 sso-server 端接口
        Map<String, Object> param = new LinkedHashMap<>();
        param.put("loginId", userId);
        Object body = SaSsoUtil.getData("/sso/userinfo", param);
        JSONObject jo = JSON.parseObject(String.valueOf(body));

        // code != 200，代表请求失败
        Integer code = jo.getInteger("code");
        if (code == null || code != SaResult.CODE_SUCCESS) {
            throw new RuntimeException(jo.getString("msg"));
        }

        // 解析
        SysUser user = jo.getObject("data", SysUser.class);
        return user;
    }

    /**
     * 获取当前登录的 User 信息
     *
     * @return User信息
     */
    public static SysUser getCurrUser() {
        return getUserById(StpUtil.getLoginIdAsLong());
    }

}
